<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="4">
        <el-input
          @input="changeInput"
          v-model="username"
          placeholder="请输入用户名"
        />
      </el-col>
      <el-col :span="4">
        <el-button type="success" @click="show = true">添加</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="oldTime" label="上次登录时间" /> </el-table
      ></el-col>
    </el-row>
    <div class="block">
      <el-pagination
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
        :total="page.total"
      ></el-pagination>
    </div>
    <UserAddDialog v-model="show" @submit="submitAdd"></UserAddDialog>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs } from "vue";
import UserAddDialog from "./userAddDialog.vue";
import { userList, addUser } from "@/api/article.js";
import { debounce } from "@/utils/utils";
import { ElMessage } from "element-plus";
import md5 from "md5";
export default {
  components: { UserAddDialog },
  setup() {
    const data = reactive({
      tableData: [],
      username: "",
      show: false,
      page: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
      },
    });
    const debounceGetData = debounce(getData, 300);
    onMounted(() => {
      getData();
    });
    function changeInput() {
      debounceGetData();
    }
    function handleCurrentChange(e) {
      data.page.pageNum = e;
      getData();
    }
    function getData() {
      userList({
        username: data.username,
        pageSize: data.page.pageSize,
        pageNum: data.page.pageNum,
      })
        .then((res) => {
          if (res.code == 200) {
            data.tableData = res.data.data;
            data.page.total = res.data.total;
          }
        })
        .catch(() => {});
    }
    function submitAdd({ item, clear }) {
      addUser({
        username: item.username,
        password: md5(item.password),
        surePassword: md5(item.surePassword),
      }).then((res) => {
        if (res.code == 200) {
          ElMessage({
            message: "添加成功！",
            type: "success",
          });
          clear();
          getData();
          data.show = false;
        }
      });
    }
    return { ...toRefs(data), handleCurrentChange, changeInput, submitAdd };
  },
};
</script>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.block {
  text-align: center;
}
</style>
